<?php

	// +----------------------------------------------------------------------
	// | 分类控制器
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\controller\cms\admin;

	use app\model\cms\Category as CategoryModel;
	use app\event\cms\Category as CategoryEvent;
	use app\event\ucenter\Action;
	use think\facade\Session;
	use yicmf\builder\Edit;
	use yicmf\builder\Table;
	use think\facade\Db;
	use think\facade\Url;
	use app\controller\admin\Common;
	use app\model\cms\Document as DocumentModel;
	use app\model\cms\Pattern as PatternModel;

	class Category1 extends Common
	{
		protected function initialize()
		{
			parent::initialize();
			$this->model = new CategoryModel();
		}

		public function _filter()
		{
		}

		public function index()
		{
			//读取规则列表
			$map = $this->_search($this->dbname);
			$map['pid'] = 0;
			//            //显示页面
			$builder = new Table();
			$builder ->setSearchPostUrl('', '')
				//            ->warning('数据自动抓取，分类请勿自行增删')
				->searchText('title', '搜索标题：', '标题')
				->buttonUpdate('update', '新增分类')
				->keyId()
				->keyTitle()
				->keyBool('is_recommend', '推荐')
				->keyBool('display', '显示列表')
				->keyMap('style', '栏目属性', CategoryModel::$style_list)
				->keyText('sort', '排序', 'sort')
				->keyText('update_time', '更新时间')
				->keyStatus()
				->data(function($where, $field) use ($map) {
					$lists = CategoryModel::where('pid', 0)->where('status', 1)->order('sort asc')->where($where)->select();
					$result = [];
					$result['code'] = 0;
					$result['data'] = [];
					foreach ($lists as $list) {
						$result['data'][] = $list;
						// 查询子集
						$children = CategoryModel::where('pid', $list['id'])->where('status', 1)->order('sort asc')->where($where)->select();
						if ($children) {
							foreach ($children as $index => $child) {
								if ($index < (count($children) - 1)) {
									$child['title'] = ' ├' . $child['title'];
								} else {
									$child['title'] = '└' . $child['title'];
								}
								$result['data'][] = $child;
								$children2 = CategoryModel::where('pid', $child['id'])->where('status', 1)->order('sort asc')->where($where)->select();
								if ($children2) {
									foreach ($children2 as $index2 => $child2) {
										if ($index2 < (count($children2) - 1)) {
											$child2['title'] = '│ ├' . $child2['title'];
										} else {
											$child2['title'] = '│ └' . $child2['title'];
										}
										$result['data'][] = $child2;
									}
								}
							}
						}
					}
					return $result;
				}, false)
				->actionUpdate()
				->actionUpdate('update?pid={$id}', '下级', function($data) {
					return 1 == $data['style'];
				})
				->actionDelete('remove?id={$id}');
			return $builder->fetch();
		}

		/**
		 * 编辑分类
		 * @access protected
		 * @author 微尘 <yicmf@qq.com>
		 */
		public function update()
		{
			if ($this->request->isPost()) { //提交表单
				$validate = $this->validate($this->request->post(), 'Category');
				if (true === $validate) {
					$event = new CategoryEvent();
					$result = $event->update($this->request->post(), $this->user);
					if (0 == $result['code']) {
						$this->_returnSuccess( $result['message'], true);
					} else {
						$this->_returnError( $result['message']);
					}
				} else {
					$this->_returnError( $validate);
				}
			} else {
				/* 获取分类信息 */
				$id = $this->request->get('id');
				$isEdit = $id ? true : false;
				if ($isEdit) {
					$data = CategoryModel::find($id);
					if ($data === false) {
						$this->_returnError( '分类不存在或者已经删除');
					}
					$cates = CategoryModel::where('pid', 0)
						->where('style',1)
						->where('id', '<>', $data['id'])
						->where('status', '>', 0)
						->select();
				} else {
					$data['style'] = 3;
					$data['pid'] = $this->request->param('pid');
					$cates = CategoryModel::where('style',1)->where('pid', 0)->where('status', '>', 0)->select();
				}
				$cate[0] = '顶级分类';
				foreach ($cates as $value) {
					$cate[$value['id']] = $value['title'];
					$children = $value->children()->where('status',1)->where('style','in','1,2')->select();
					if ($children) {
						foreach ($children as $child) {
							$cate[$child['id']] = '   ├' . $child['title'];
						}
					}
				}

				$patterns = PatternModel::where('extend','<>',0)->where('status',1)->where('is_show',1)->column('title','id');
				$builder = new Edit();
				$builder->title('编辑分类栏目')
					->keySelect('pid', '上级分类', $cate, '所属的上级分类')
					->keyTextInline('title', '分类名称', '名称不能为空', '', 'required')
					->keyTextInline('name', '分类标识', '英文字母，填写http开头的域名跳转链接', '', 'required|alphaDash')
					->keyRadio('style', '栏目属性', CategoryModel::$style_list, '单页属性不可发布内容')
					->keyBelongsToMany('patterns', '模型', $patterns,'列表绑定内容模型')
					->keySwitch('is_recommend', '是否推荐')
					->keySwitch('display', '可见性', '当前分类显示在列表')
					->keyRadio('is_check', '是否审核', ['不需要', '需要'], '发布的内容是否需要审核')
					->keySort()
					->keyNumber('list_row', '列表行数', '', 15)
					->keyTextArea('keywords', '关键词')
					->keyTextArea('description', '描述')
					->keyEditor('content', '栏目内容', '一般用于单页分类详情介绍')
					->group('常规选项', 'id,pid,title,style,name,pattern_id,template_detail,url,is_recommend,content,patterns')
					->group('高级选项', 'display,sort,keywords,description,list_row,is_check')
					//                                    ->group('栏目内容', 'content')
					->setTrigger('style', '1', '')
					->setTrigger('style', '2', '')
					//                                    ->setTrigger('style', '2', 'pattern_id,is_check,list_row,template_detail')
					->setTrigger('style', '3', 'content')
					->data($data)
					//                    ->explain('栏目内容是替代原来栏目单独页的更灵活的一种方式，通常用于企业简介之类的用途。')
					->buttonSubmit('', '保存');
				//                    ->buttonClose();
				return $builder->fetch();
			}
		}

		/**
		 * 删除一个分类
		 * @access protected
		 * @author 微尘 <yicmf@qq.com>
		 */
		public function remove()
		{
			$category = CategoryModel::where('status', 1)->where('id', $this->request->param('id'))->find();
			if (!$category) {
				$this->_returnError( '分类不不存在');
			} else {
				if (CategoryModel::where('status', 1)->where('pid', $this->request->param('id'))->find()) {
					$this->_returnError( '请先删除该分类下的子分类');
				}
				// 是否有子集
				if (DocumentModel::where('status', '>', -2)->where('category_id', $category['id'])->find()) {
					$this->_returnError( '请先删除该分类下的文档');
				}
				$category['status'] = -2;
				$category->save();
				$this->_returnSuccess( '删除分类成功');
			}
		}

	}